package com.huika.dealontop.control.homepage.utils.fourad.basefourad;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.huika.dealontop.R;
import com.huika.dealontop.control.nearby.activity.MerchantDetailActivity;
import com.huika.dealontop.control.shops.activity.ProductDetailsActivity1;
import com.huika.dealontop.support.domain.HomePageAdvertisementSeatInfo;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.webview.BaseWebViewAct;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;

/**
 * Created by cailu on 2016/1/13.
 */
public abstract class BaseFourAd implements View.OnClickListener {
    protected Activity mContext;
    protected ArrayList<HomePageAdvertisementSeatInfo> mHomePageFourAdvertisementLists;
    protected View mView;
    protected ImageView mAdvertisementOne;
    protected ImageView mAdvertisementTwo;
    protected ImageView mAdvertisementThree;
    protected ImageView mAdvertisementFour;
    protected int mWidthPixels;
    private ImageView mIv;

    protected BaseFourAd(Activity context, ArrayList<HomePageAdvertisementSeatInfo> info) {
        mContext = context;
        mHomePageFourAdvertisementLists = info;
        initView();
    }

    protected void initView() {
        mView = initRoot();
        mAdvertisementOne = (ImageView) mView.findViewById(R.id.homepage_advertisement_one);
        mAdvertisementTwo = (ImageView) mView.findViewById(R.id.homepage_advertisement_two);
        mAdvertisementThree = (ImageView) mView.findViewById(R.id.homepage_advertisement_three);
        mAdvertisementFour = (ImageView) mView.findViewById(R.id.homepage_advertisement_four);
        DisplayMetrics displayMetrics = UIUtils.getDisplayMetrics();
        mWidthPixels = displayMetrics.widthPixels;

        if (mAdvertisementOne != null) {
            mAdvertisementOne.setOnClickListener(this);
        }
        if (mAdvertisementTwo != null) {
            mAdvertisementTwo.setOnClickListener(this);
        }
        if (mAdvertisementThree != null) {
            mAdvertisementThree.setOnClickListener(this);
        }
        if (mAdvertisementFour != null) {
            mAdvertisementFour.setOnClickListener(this);
        }
        initWidget();
    }

    protected abstract void initWidget();

    protected abstract void widgetClick(View v);

    protected abstract View initRoot();

    protected void setLayoutParamsHW(ImageView iv, int width, int height) {
        ViewGroup.LayoutParams lp = iv.getLayoutParams();
        lp.width = width;
        lp.height = height;
        iv.setLayoutParams(lp);
    }

    protected void imageLoader(String url, ImageView iv) {
        mIv = iv;
        //  1.完成ImageLoaderConfiguration的配置
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext)
                .memoryCacheExtraOptions(480, 800)          // default = device screen dimensions
                        //.discCacheExtraOptions(480, 800, Bitmap.CompressFormat.JPEG, 75, null)
                        //.taskExecutor()
                        //.taskExecutorForCachedImages()
                .threadPoolSize(3)                          // default
                .threadPriority(Thread.NORM_PRIORITY - 1)   // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13)              // default
                        //.discCache(new UnlimitedDiscCache(cacheDir))// default
                .discCacheSize(50 * 1024 * 1024)        // 缓冲大小
                .discCacheFileCount(100)                // 缓冲文件数目
                .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                        //.imageDownloader(new BaseImageDownloader(context)) // default
                        //.imageDecoder(new BaseImageDecoder()) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();

//  2.单例ImageLoader类的初始化
        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);

//  3.DisplayImageOptions实例对象的配置
//      以下的设置再调用displayImage()有效，使用loadImage()无效
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.morenpic)          // image在加载过程中，显示的图片
                .showImageForEmptyUri(R.mipmap.morenpic)  // empty URI时显示的图片
                .showImageOnFail(R.mipmap.morenpic)       // 不是图片文件 显示图片
                .resetViewBeforeLoading(false)  // default
                .delayBeforeLoading(1000)
                .cacheInMemory(false)           // default 不缓存至内存
                .cacheOnDisc(false)             // default 不缓存至手机SDCard
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)// default
                .bitmapConfig(Bitmap.Config.ARGB_8888)              // default
                .displayer(new SimpleBitmapDisplayer()) // default 可以设置动画，比如圆角或者渐变// default
                .build();

//  4图片加载
//  4.1 调用displayImage
//        imageLoader.displayImage(
//                url,        /*
//                    String imageUri = "http://site.com/image.png";      // from Web
//                    String imageUri = "file:///mnt/sdcard/image.png";   // from SD card
//                    String imageUri = "content://media/external/audio/albumart/13"; // from content provider
//                    String imageUri = "assets://image.png";             // from assets
//                    */
//                iv,      // 对应的imageView控件
//                options);       // 与之对应的image显示方式选项

//  4.2 调用loadImage
//      对于部分DisplayImageOptions对象的设置不起作用
        imageLoader.loadImage(
                url,
                options,
                new MyImageListener()); //ImageLoadingListener

    }

    @Override
    public void onClick(View v) {
        HomePageAdvertisementSeatInfo homePageAdvertisementSeatInfo = null;
        switch (v.getId()) {

            case R.id.homepage_advertisement_one:
                homePageAdvertisementSeatInfo = mHomePageFourAdvertisementLists.get(0);
                break;
            case R.id.homepage_advertisement_two:
                homePageAdvertisementSeatInfo = mHomePageFourAdvertisementLists.get(1);
                break;
            case R.id.homepage_advertisement_three:
                homePageAdvertisementSeatInfo = mHomePageFourAdvertisementLists.get(2);
                break;
            case R.id.homepage_advertisement_four:
                homePageAdvertisementSeatInfo = mHomePageFourAdvertisementLists.get(3);
                break;
        }
        switch (homePageAdvertisementSeatInfo.getBannerType()) {
            case "0":
                if (TextUtils.isEmpty(homePageAdvertisementSeatInfo.getAdName())) {
                    return;
                }
                intentWebView(homePageAdvertisementSeatInfo.getAdUrl(), homePageAdvertisementSeatInfo.getAdName());
                break;
            case "1":
                //showToastMsg("1商品");
                if (TextUtils.isEmpty(homePageAdvertisementSeatInfo.getProductID())) {
                    return;
                }
                Intent intent = new Intent(mContext, ProductDetailsActivity1.class);
                intent.putExtra(ProductDetailsActivity1.PRODUCT_ID, homePageAdvertisementSeatInfo.getProductID());
                showActivity(mContext, intent);
                break;
            case "2":

                if (TextUtils.isEmpty(homePageAdvertisementSeatInfo.getProductID())) {
                    return;
                }

                Intent intent2 = new Intent(mContext, MerchantDetailActivity.class);
                intent2.putExtra(MerchantDetailActivity.Merchant_ID, homePageAdvertisementSeatInfo.getProductID());
                showActivity(mContext, intent2);
                break;
        }
        widgetClick(v);
    }

    public void intentWebView(String url, String name) {
        Intent intent = new Intent(mContext, BaseWebViewAct.class);
        intent.putExtra(BaseWebViewAct.PAGE_URL, url);
        intent.putExtra(BaseWebViewAct.PAGE_TITLE, name);
        mContext.startActivity(intent);
    }

    public void showActivity(Activity aty, Intent it) {
        aty.startActivity(it);
        mContext.overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
    }


    class MyImageListener extends SimpleImageLoadingListener {

        @Override
        public void onLoadingStarted(String imageUri, View view) {
            mIv.setImageResource(R.mipmap.morenpic);
            super.onLoadingStarted(imageUri, view);

        }

        @Override
        public void onLoadingFailed(String imageUri, View view,
                                    FailReason failReason) {
            mIv.setImageResource(R.mipmap.morenpic);
            super.onLoadingFailed(imageUri, view, failReason);
        }

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            mIv.setImageBitmap(loadedImage);
            super.onLoadingComplete(imageUri, view, loadedImage);
            Toast.makeText(mContext,"dfadf",Toast.LENGTH_LONG).show();
            initImageLoader();
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            mIv.setImageResource(R.mipmap.morenpic);
            super.onLoadingCancelled(imageUri, view);
        }

    }
    protected void initImageLoader(){};
}
